<?php

namespace app\index\controller;


use think\facade\App;
use app\BaseController;
use think\facade\View;

class ViewLog extends BaseController
{
    protected $indexDirPath = [];
    

    public function __construct(App $app = null)
    {
        config('app_trace', false);
    }

    public function index()
    {
        $runtime = str_replace("index","",App::getRuntimePath());
        $this->indexDirPath = [
            $runtime . '/api/log' => 'api请求记录',
            $runtime . '/api/execption' => 'api请求异常',
            App::getRuntimePath(). '/execption' => 'index请求异常',
            App::getRuntimePath(). '/log' => 'index请求异常',
        ];


        $colors = [
            'FF7F24', '698B22', '8B6914', 'CDCD00', 'CD3278', '848484', '8EE5EE', '8B6914', 'FF7F24', '8B6914',
            'FF7F24', '698B22', '8B6914', 'CDCD00', 'CD3278', '848484', '8EE5EE', '8B6914', 'FF7F24', '8B6914',
        ];

        $assignPath = [];
        foreach ($this->indexDirPath as $path => $val) {
            if (is_dir($path)) {
                $assignPath[urlencode($path)] = $val;
            }
        }

        View::assign('dirList', $assignPath);
        View::assign('colors', $colors);
        return View::fetch();
    }

    public function view()
    {
        $dirpath = input('dirpath');
        $data = [];
        if ($dirpath && is_dir($dirpath)) {
            foreach (scandir($dirpath) as $name) {
                $filePath = $dirpath . '/' . $name;
                if ($name == '.' || $name == '..') {
                    continue;
                } else {
                    if (is_dir($filePath)) {
                        $data[] = ['name' => $name, 'url' => urlencode($filePath), 'size' => '', 'time' => '', 'isfile' => 0];
                    } elseif (is_file($filePath)) {
                        $data[] = [
                            'name' => $name, 'url' => urlencode($filePath),
                            'size' => filesize($filePath), 'time' => date('Y-m-d H:i:s', filemtime($filePath)), 'isfile' => 1
                        ];
                    }
                }
            }

            View::assign('data', $data);
            return View::fetch('view');
        } elseif ($dirpath && is_file($dirpath)) {
            $ext = pathinfo($dirpath, PATHINFO_EXTENSION);
            if ($ext == 'html' || $ext == '.html' || $ext == '.htm' || $ext == 'htm') {
                return file_get_contents($dirpath);
            } else {

                header('Content-Type: text/plain');
                echo file_get_contents($dirpath);
                exit;
            }
        }
    }
}

